<template>
  <div class="app-init gouwuche-page">
    <header-back :title="pageTitle"></header-back>
    <div v-if="stepData.length > 0" ref="view01" class="app-init scroll-box aftersale-apply-other task-step">
      <cube-slide :initial-index="initPage.currentStep" :auto-play="false" :allow-vertical="true" :loop="false" ref="slide" @change="changePage">
        <cube-slide-item v-for="(item, index) in stepData" :key="index">
          <div class="step-page">
            <div class="step-head">
              <span class="title">{{item.name}}</span>
              <span class="time-title">任务将在 <span  style="color: #ff5000">{{other.current_WEB | countDown(other.down_times)}}</span> 后自动截止</span>
              <span class="fr">{{index+1}}/{{stepData.length}}</span>      
            </div>   
            <p v-if="item.name == '查找商品'" class="account-user">请使用{{initPage.platname}}账号： <span class="user">{{initPage.account}}</span>  进行操作</p>     
            <div class="step-content">
              <div class="app-content">
                <div class="step-picture-example">
                  <div v-if="item.name == '查找商品'" class="step-content-app clear">
                    <img class="goods-logo" :src="initPage.exampic" preview="1" alt="">
                    <div class="goods-info">
                      <div class="i-item">
                        <span class="i-value fr">{{initPage.store}}</span>
                        <span class="i-name">店铺名称</span>
                      </div>
                      <div class="i-item">
                        <span class="i-value fr">{{initPage.priceGoods}} 元</span>
                        <span class="i-name">成交价格</span>
                      </div>
                    </div> 
                  </div>
                  <div class="step-picture-example step-desc clearfix">
                    {{item.memo}}
                  </div> 
                  <div v-if="item.name == '查找商品'" class="task-name">
                    <span class="i-name">任务名称</span>
                    <span class="i-value fr ellipsis" style="width: 60%; text-align: right">{{initPage.name}}</span>
                  </div>
                  <!-- browse: 纯展示， 无任何交互 -->
                  <div class="" v-for="(i, idx) in item.detailArr.browse" v-if="i.usrtype == 1" :key="idx"> 
                    <!-- cateFlg: 1 文本   2. 图片 -->
                    <div class="step-content-app clearfix" v-if="i.cateFlg == 2">
                      <div class="step-title">{{i.name}}</div>
                      <div class="step-info">
                        <img v-lazy="i.value" :preview="idx + 1" :preview-text="i.name">
                      </div>
                    </div>
                    <div class="step-content-app clearfix" v-else>
                      <div class="step-title">{{i.name}}</div>
                      <div v-if="i.name != '关键词'" class="step-info">{{i.value}}</div>
                      <div v-else class="key-word step-info">
                        <span class="i-value">{{i.value[other.idx]}}</span>   
                        <span class="i-btn" @click="changeIdx(i)">换一组</span>                        
                      </div>
                    </div>
                  </div>
                </div>
                <div style="margin-bottom: .3rem" class="clearfix" v-for="(i, idx) in item.detailArr.edit">
                  <div class="" v-if="i.cateFlg == 1">
                    <div class="clearfix">
                      <div class="step-title" style="line-height: 1.2; width: 35%">{{i.name}}</div>
                      <div class="step-info">{{i.example}}</div>
                    </div>
                    <div class="step-input">
                      <textarea style="height: 1.3rem" :placeholder="i.example" v-model="i.value"></textarea>
                    </div>
                  </div>
                  <div class="" v-if="i.cateFlg == 2">
                    <div class="clearfix">
                      <div class="step-title">示例图片</div>
                      <div class="step-info">
                        <img v-lazy="i.example" preview="1" preview-text="示例图片">
                      </div>
                    </div>
                    <div class="step-upload">
                      <cube-upload
                      :action="action"
                      :simultaneous-uploads="1"
                      :multiple="false"
                      @file-removed="fileremoved(i, $event)"
                      @file-success="filesuccess(i, $event)"
                      :max="3"
                      :processFile="processFile"/>
                    </div>
                  </div>
                  <div class="" v-if="i.cateFlg == 3">
                    <div class="step-input">
                      <div class="step-title" style="width: auto">{{i.wervalue}}</div>
                      <textarea placeholder="请输入正确答案" v-model="i.value" style="margin-top: .3rem; height: 1.3rem"></textarea>
                    </div>
                  </div>
                  <div class="" v-if="i.cateFlg == 4">
                    <div style="margin-bottom:.6rem" class="step-title dd">请下载下方图片，并且在评价的时候使用这些图片</div>
                    <div class="clearfix">
                      <div class="step-title dd">示例图片</div>
                      <div class="step-info dd">
                        <img v-for="(pic, pic_idx) in i.example" :key="pic_idx" v-lazy="pic.url" :preview="pic_idx + 1" preview-text="示例图片">
                      </div>
                    </div>
                    <div v-if="i.group && (i.group != '')" class="step-input">
                      <div class="step-title" style="width: auto">评价要点： {{i.group}}</div>
                    </div>
                  </div>
                  <!-- 截图反馈 -->
                  <div class="" v-if="i.cateFlg == 5">
                    <div class="clearfix">
                      <div class="step-title">{{i.name}}</div>
                      <div class="step-info">{{i.example}}</div>
                    </div>
                    <div class="step-upload">
                      <cube-upload
                      v-model="i.other"
                      :action="action"
                      :simultaneous-uploads="1"
                      :multiple="false"
                      @file-removed="fileremoved(i, $event)"
                      @file-success="filesuccess(i, $event)"
                      :max="3"
                      :processFile="processFile"/>
                    </div>
                  </div>
                  <!-- 核对反馈 -->
                  <div class="check-input" v-if="i.cateFlg == 6">
                    <div class="check-name">{{i.name}}</div>
                    <div class="step-input">
                      <textarea :placeholder="`请根据示例文本类似的${i.name}`" v-model="i.value"></textarea>
                    </div>
                    <div v-if="!boo.hasChecked" class="btn-primary" @click="checkUrl(i)">粘贴并核对</div>
                    <div v-else class="btn-primary success">核对成功</div>
                  </div>
                </div>
              </div>
            </div>
            <div class="step-operate" v-if="!boo.waiting">
              <div class="btn-primary" v-if="(index == initPage.currentStep) && (other.state == 0)" @click="doTask(item, index)">提交</div>
              <div class="btn-primary disabled" v-else-if="(index == initPage.currentStep) && (other.state != 0)" >等待商家审核</div>
              <div class="btn-primary disabled" v-else>提交</div>
            </div>
            <div class="step-operate" v-else>
              <div class="btn-primary disabled">{{other.current_time | countDown(other.end_time)}} 后提交</div>
            </div>
          </div>
        </cube-slide-item>
      </cube-slide>
    </div>
  </div>
</template>
<script>

  import headerBack from '@/components/header-back'
  import VueDB from '../../util/vue-db/vue-db-long'
  let DB = new VueDB()
  export default {
    name: 'step',
    data() {
      return {
        https: this.$api.task,
        start: 1525293470350,
        initPage: {
          currentStep: 0, //按数组下标
        },
        timer: null,
        other: {
          idx: 0,
          current_time: 0, //预约时间   当前时间
          current_WEB: 0, //截止时间    当前时间
          end_time: 0, //任务可做时间
          down_times: 0, //任务截止时间
          state: 0, //下单步骤是否需要冻结按钮
        },
        boo: {
          hasChecked: true, //是否进行过核对
          waiting: false, //是否需要等待
        },
        action: {
          target: this.apiUrl + 'user/uplodimg',
          fileName: 'pic',
          data: {
            dir: 'app_task',
          },
          headers: {
            token: DB.getItem('token')
          },
        },
        pageTitle: '进行任务',
        text: "",
        prodlink: '',
        stepData: [],
        pictureArr: []
      }
    },
    filters: {
      countDown(start, end){
        let dd = 0, hh = 0, mm = 0, ss = 0
        let rightTime = end - start;
        if (rightTime > 0) {
          dd = Math.floor(rightTime / 1000 / 60 / 60 / 24);
          hh = Math.floor((rightTime / 1000 / 60 / 60) % 24);
          mm = Math.floor((rightTime / 1000 / 60) % 60);
          ss = Math.floor((rightTime / 1000) % 60);
        }
        hh = hh < 10 ? '0'+hh : hh
        mm = mm < 10 ? '0'+mm : mm
        ss = ss < 10 ? '0'+ss : ss
        return dd + "天" + hh + "：" + mm + "：" + ss
      },
    },
    components: {
      headerBack,
    },
    mounted() {
      this.getDetail()
    },
    methods: {
      countDownStep(){
        let _self = this
        _self.boo.waiting = true
        if(_self.timer){
          clearInterval(_self.timer)
        }
        _self.timer = setInterval(()=> {
          if((_self.other.end_time - _self.other.current_time) <= 1000){
            _self.boo.waiting = false
          }
          _self.other.current_time +=  1000
          _self.other.current_WEB +=  1000
        }, 1000);
      },
      getDetail(){
        let _self = this
        const toast = this.$createToast({
          time: 60000,
          txt: '加载中',
          mask: true
        })
        toast.show()
        let params = {
          id: this.$router.currentRoute.params.id
          // id: '55535'
        }
        let success = (res)=>{
          toast.hide()
          res = res.data
          if(res.code == 200){
            if(res.data.step == res.data.stepArr.length) return _self.$router.replace({path: "/mine/myTask"})
            _self.initPage = {
              currentStep: Number(res.data.step),
              store: res.data.merchant_store,
              priceGoods: res.data.priceGoods,
              account: res.data.account,
              name: res.data.name,
              platname: res.data.platname,
              exampic: res.data.exampic
            }
            _self.other.current_time = JSON.parse(JSON.stringify(res.data.current * 1000)) //预约时间当前时间
            _self.other.current_WEB = JSON.parse(JSON.stringify(res.data.current * 1000)) //截止时间当前时间
            _self.other.end_time = res.data.endtime * 1000 //任务预约时间
            _self.other.down_times = res.data.down_times * 1000 //任务截止时间
            _self.countDownStep()

            res.data.stepArr.forEach(item=>{
              item.detailArr.browse.forEach(i=>{
                if(i.name == '关键词'){
                  i.value = i.value.replace(/，/g, ",").split(',')
                }
              })
              item.detailArr.edit.forEach(i=>{
                if(i.cateFlg == 4 || i.cateFlg == 5){
                  i.other = i.value
                  if(i.other != ''){
                    let m = i.other
                    m.forEach((pic, idx)=>{
                      m[idx] = {
                        url: pic,
                        status: 'success',
                        progress: 1,
                        response: {
                          data: pic,
                          message: "保存图片成功",
                          status: "200",
                        }
                      }
                    })
                  }else{
                    i.other = []
                  }               
                }
                if(i.cateFlg == 6) {
                  _self.boo.hasChecked = false
                }
              })
            })
            _self.stepData = res.data.stepArr
          }else{
            _self.$createToast({
              txt: res.message,
              type: 'txt'
            }).show()
          }
        }
        _self.$axios.post(_self.https.step, params, success)
      },
      upload(dataurl, filename, cb){
        let arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
          bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
        while(n--){
          u8arr[n] = bstr.charCodeAt(n);
        }
        let file = new File([u8arr], filename, {type:mime})
        cb(file)
      },
      processFile(file, next){
        let _self = this
        const maxSize = 1 * 1024 * 1024 // 1M
        let quality = 0.2
        if(file.size > (12 * maxSize)){ quality = 0.05}
        if(file.size > (8 * maxSize) && file.size <= (12 * maxSize)){ quality = 0.1 }
        if(file.size < (8 * maxSize)){ quality = 0.2}
        let opt = {
          quality: quality,
        }
        _self.$lrz(file, opt).then((rst)=>{
          _self.upload(rst.base64, 'file.png', next)
        })
      },
      fileremoved(item, res){
        let _self = this
        res = res.response
        if(res.status == 200){
          item.value.pop(res.data)
        }else{
          _self.$createToast({
            txt: res.message,
            type: 'txt'
          }).show()
        }
      },
      filesuccess(item, res){
        let _self = this
        res = res.response
        if(res.status == 200){
          item.value = item.value == '' ? [] : item.value   
          item.value.push(res.data)
        }else{
          _self.$createToast({
            txt: res.message,
            type: 'txt'
          }).show()
        }
      },
      copyUrl(item) {
        var that = this
        that.$copyText(item.example).then(function (e) {
          that.toast = that.$createToast({
            txt: "复制成功",
            type: 'txt'
          })
          that.toast.show()
          item.urlFlag = 0
        }, function (e) {
          that.toast = that.$createToast({
            txt: "复制失败",
            type: 'txt'
          })
          that.toast.show()
        })
      },
      doTask(item, index) {
        let _self = this
        let str = ''
        if(!_self.boo.hasChecked) return this.$createDialog({
          type: 'alert',
          title: '错误提示',
          content: '请先进行产品核对',
          icon: 'cubeic-alert'
        }).show()
        item.detailArr.edit.forEach(i=>{
          if(i.value == ''){
            if(i.cateFlg == 2){
              str = `请上传反馈内容`
            }else{
              str = `请填写反馈内容`
            }
          }else{
            if((i.cateFlg == 3) && (i.value != i.example)) return str = `信息校验错误，请检查`
          }
        })
        if( str != '' ) return this.$createDialog({
          type: 'alert',
          title: '错误提示',
          content: str,
          icon: 'cubeic-alert'
        }).show()
        let kk = JSON.parse(JSON.stringify(_self.stepData[_self.initPage.currentStep].detailArr.edit))
        kk.forEach(kk=>{
          delete kk.other
        })
        let params = {
          id: _self.$router.currentRoute.params.id,
          step: _self.initPage.currentStep + 1,
          pictureArr: JSON.stringify(kk)
        }
        let success = (res)=>{
          res = res.data
          if(res.code == 200 ){
            if((res.data.flag == 1) && (DB.getItem('app_from').toString()) && (DB.getItem('app_from').toString() == 'ad')) return _self.$router.replace({path: "/ad/complete", query: {id: _self.$router.currentRoute.params.id}})
            _self.initPage.currentStep ++
            if(_self.initPage.currentStep >= _self.stepData.length){              
              _self.$router.replace({path: "/mine/myTask"})
            }else{
              _self.other.current_time = JSON.parse(JSON.stringify(res.data.current * 1000)) //预约时间当前时间
              _self.other.current_WEB = JSON.parse(JSON.stringify(res.data.current * 1000)) //截止时间当前时间
              _self.other.end_time = res.data.endtime * 1000 //任务预约时间
              _self.other.state = res.data.state
              if(_self.timer){
                clearInterval(_self.timer)
              }
              _self.countDownStep()
            }
          }else{
            _self.$createToast({
              txt: res.message,
              type: 'txt'
            }).show()
          }
        }
        _self.$axios.post(_self.https.dotask, params, success)        
      },
      changeIdx(i){
        let _self = this
        let lgn = i.value.length
        if(_self.other.idx < (lgn - 1)){
          _self.other.idx ++
        }else{
          _self.other.idx = 0
        }
      },
      checkUrl(item){
        let _self = this
        if(item.value == '') return this.$createToast({
          type: 'txt',
          txt: '核对内容不能为空'
        }).show()
        let params = {
          id: _self.$router.currentRoute.params.id,
          check: item.value
        }
        const toast = this.$createToast({
          time: 60000,
          txt: '加载中',
          mask: true
        }).show()
        let success = (res)=>{
          res = res.data
          toast.hide()
          if(res.code == 200){
            _self.boo.hasChecked = true
          }else{
            _self.$createToast({
              type: 'txt',
              txt: res.message
            }).show()
          }
        }
        _self.$axios.post(_self.https.checkUrl, params, success)
      },
    },
    beforeDestroy() {
      if(this.timer) { //如果定时器还在运行 或者直接关闭，不用判断
        clearInterval(this.timer); //关闭
      }
    }
  }
</script>

<style type="text/sass" lang="sass" scoped>
  @import '../../assets/sass/util'
  .step-operate
    position: absolute
    left: 0
    width: 100%
    bottom: .3rem
    .btn-primary
      margin: 0px auto
      border-radius: 2rem
      &.disabled
        background: #ccc
  .dd
    width: auto !important
  .time-title
    letter-spacing: normal
    color: #333
    font-size: .32rem
  .check-input
    .check-name
      font-size: .32rem
      line-height: 1.4
    .btn-primary
      border-radius: 2rem
      font-size: 0.32rem;
      border-radius: 0.15625rem;
      letter-spacing: 0;
      line-height: .7rem
      width: 40%
      margin-top: .2rem
      &.success
        color: #fff
        background: #67c23a
  .ellipsis
    overflow: hidden
    text-overflow: ellipsis
    white-space: nowrap 
  .step-desc
    background: #FEF0F0
    color: #f56c6c
    padding: .2rem !important
    font-size: .32rem
    border-radius: .2rem
    line-height: 1.4
    text-align: justify
  .key-word
    .i-btn
      margin-left: .2rem
      color: #1A78FF
      text-decoration: underline
  .task-name
    margin-top: .5rem
    margin-bottom: .3rem
    color: #333
    font-size: .34rem
  .account-user
    color: #333
    font-size: .36rem
    padding: 0 .2rem .2rem
    border-bottom: 1px solid #f4f4f4
    .user
      color: #ff5000
  .step-upload, .step-input
    margin-top: .3rem
  .hiddenInput
    opacity: 0
    position: absolute
  .upload-container
    display: block
    width: 2rem
    height: 2rem
    img
      display: block
      width: 100%
      height: 100% 
    .iconfont
      font-size: 1.2rem
      color: #ccc
  .app-content
    // height: 9.5rem
    padding-bottom: 1.2rem
    overflow-x: hidden
  .clearfix 
    *zoom: 1
  .clearfix:before,.clearfix:after
    display: table
    line-height: 0
    content: ""
  .clearfix:after
    clear: both
  .example-content
    font-size: .36rem !important
  .step-content-app
    margin-bottom: .2rem
    .goods-logo
      float: left
      width: 2.2rem
      height: 2.2rem
      border-radius: .2rem
    .goods-info
      margin-left: 2.5rem
      padding-top: .3rem
      .i-item
        margin-bottom: .2rem        
        .i-name
          color: #999
          display: block
        .i-value
          text-align: right
        .i-name, .i-value
          font-size: .32rem
          width: 45%
  .cube-slide-item
    padding: .7rem .4rem
    .step-page
      position: relative
      overflow: hidden
      height: 98%
      background: #ffffff
      border-radius: .1rem
      transform: translateY(-2%)
      box-shadow: 1px 4px 10px 2px #CCC
      -webkit-box-shadow: 1px 4px 10px 2px #CCC
      -moz-box-shadow: 1px 4px 10px 2px #CCC
      .step-head
        line-height: 1.2rem
        font-size: .39rem
        color: #ff5000
        letter-spacing: .1rem
        padding: 0 .2rem
        .title
          letter-spacing: normal
      .step-content
        // height: calc(100vh - 6rem)
        height: 12.3rem
        padding: .2rem .6rem
        overflow: scroll
        .step-title
          float: left
          width: 28%
          color: #333333
          font-size: .34rem
        .step-info
          width: 46%
          float: right
          line-height: 1.2
          font-size: .34rem
          // color: #3ca0e6
          color: #ff5000
          text-align: right
          img
            width: 2rem
            height: 2rem
            margin-right: .1rem
        .step-input
          textarea
            background: #f4f4f4
            box-sizing: border-box
            padding: .2rem
            width: 100%
            height: 1.5rem
            border: none
            color: #666666
            font-size: .36rem
          textarea::-webkit-input-placeholder
            color: #cccccc
            font-size: .36rem
        .step-input-example
          margin-top: .2rem
          padding-top: .2rem
          margin-bottom: .4rem
          border-top: 1px solid #f4f4f4
          .example-head
            font-size: .38rem
          .example-content
            margin: .4rem 0 .4rem .4rem
            color: #3ca0e6
        .step-picture-example
          padding: .15rem 0 .2rem
          margin-bottom: .2rem
          // padding-bottom: .5rem
          border-bottom: 1px solid #f4f4f4
          .example-head
            font-size: .38rem
          .example-content
            margin: .4rem 0 .4rem .4rem
            color: #3ca0e6
            img
              float: left
              width: 2rem
              height: 2rem
              margin-right: .1rem
        .step-picture
          margin-left: 0.48rem
          img
            float: left
            width: 2rem
            height: 2rem
            margin-right: .1rem
</style>
